<?php

namespace app\controller;

//玩家宠物控制器
use app\service\UserPetService;
use think\facade\Db;

class  UserPetController extends Base
{

    //玩家宠物列表
    public function list()
    {
        $user_id = $this->user_id;
        $res = (new UserPetService())->list($user_id);
        return json($res);
    }

    //兑换宠物
    public function exchange()
    {

        try {
            Db::startTrans();
            //兑换码
            $code = $this->request->post('code', null);
            //是否强制绑定
            $force = $this->request->post('force', 0);
            $res = (new UserPetService())->add($this->user, $code, $force);
            if (!$res['code']) {
                Db::rollback();
            } else {
                Db::commit();
            }
        } catch (\Exception $e) {
            Db::rollback();
            return json(apiError($e));
        }
        return json($res);
    }

    //设置宠物昵称和对我的称呼
    public function set_name()
    {
        $user_id = $this->user_id;
        //宠物id
        $user_pet_id = $this->request->post('user_pet_id', null);
        //昵称
        $cn_name = $this->request->post('cn_name', null);
        //对我的称呼
        $call_name = $this->request->post('call_name', null);

        $res = (new UserPetService())->set_nickname($user_id, $user_pet_id, $cn_name, $call_name);
        return json($res);
    }

    //喂养宠物
    public function feed()
    {
        $user_id = $this->user_id;
        //宠物id
        $user_pet_id = $this->request->post('user_pet_id', null);
        //食物id
        $user_prop_id = $this->request->post('user_prop_id', null);
        //喂养数量
        $num = $this->request->post('num', 1);

        //开启事务
        Db::startTrans();
        try {
            $res = (new UserPetService())->feed($user_id, $user_pet_id, $user_prop_id, $num);
            if (!$res['code']) {
                Db::rollback();
            } else {
                Db::commit();
            }
            return json($res);
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }


    }


}
